<?php

namespace frontend\modules\custom\models\forms;

use common\components\fenzhangtong\FenZhangTong;
use common\models\db\CustomBankCard;
use common\models\db\User;
use common\models\db\UserRegisterInviteCode;
use common\Tools;
use common\queues\LogFengZhangTongSend;
use wodrow\yii2wtools\tools\ArrayHelper;
use wodrow\yii2wtools\tools\Model;
use yii\bootstrap\Html;

class Custom extends \common\models\db\Custom
{
    public $username;
    public $password;
    public $rePassword;
    public $code;

    public function attributeLabels()
    {
        $attributeLabels = parent::attributeLabels();
        $attributeLabels = ArrayHelper::merge($attributeLabels, [
            'username' => "登录用户名",
            'password' => "登录密码",
            'rePassword' => "确认登录密码",
            'code' => "注册邀请码",
        ]);
        return $attributeLabels;
    }

    public function rules()
    {
        $rules = parent::rules();
        $rules = ArrayHelper::merge($rules, [
            [['username', 'password', 'rePassword', 'code'], 'trim'],
            [['username', 'password', 'rePassword', 'code'], 'required'],
            [['code'], 'exist', 'targetClass' => UserRegisterInviteCode::class, 'targetAttribute' => 'code'],
            [['code'], 'checkCode'],
            [['username'], 'match', 'pattern' => "/^([a-zA-Z0-9_\u4e00-\u9fa5]{5,16})$/"],
            [['password'], 'match', 'pattern' => "/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/", 'message' => "至少6个字符，至少1个大写字母，1个小写字母和1个数字,不能包含特殊字符"],
            [['rePassword'], 'compare', 'compareAttribute' => 'password'],
        ]);
        return $rules;
    }

    public function checkCode($attribute, $params)
    {
        $inviteCode = UserRegisterInviteCode::findOne(['code' => $this->code]);
        if (!$inviteCode) {
            $this->addError($attribute, "无效的邀请码");
        }
        if ($inviteCode->created_at + $inviteCode->period < YII_BT_TIME){
            $this->addError($attribute, "邀请码已过期");
        }
    }

    public function beforeValidate()
    {
        $this->notify_url = \Yii::$app->apiTool->generateUrl('/notify/fzt-user-register', ['username' => $this->username, 'id_no' => $this->id_no]);
        $this->return_url = \Yii::$app->urlManagerFztadmin->createAbsoluteUrl(['/site/login']);
        return parent::beforeValidate();
    }

    /**
     * @param FenZhangTong $fzt
     * @return bool
     * @throws \Exception
     */
    public function register(&$fzt)
    {
        $transId = uniqid();
        $params = [
            'platNo' => $this->plat_no, // 商户平台在分账通注册的平台编号
            'transId' => $transId, // 请求业务流水号
            'custName' => $this->cust_name, // 姓名
            'idType' => $this->id_type, // 证件类型：（A-身份证 E-港澳居民往来大陆通行证 F-台湾居民往来大陆通行证）
            'idNo' => $this->id_no, // 证件号码
            'mobileNo' => $this->mobile_no, // 预留手机号码
            'openBank' => $this->open_bank, // 开户银行，行号(支持的银行列表参考5.2,对应行号在bankCode.csv里提供)
            'cardNo' => $this->card_no, // 卡号
            'notifyUrl' => $this->notify_url, // 通知回调地址
            'returnUrl' => $this->return_url, // 交易完成后页面跳转地址
        ];
        $params['gender'] = $this->gender ?? null; // 性别  M-男  F-女
        $params['birthDay'] = $this->birth_day ?? null; // 出生日期  YYYYMMDD
        $params['email'] = $this->email ?? null; // 电子邮箱地址
        $params['legalExpireDate'] = $this->legal_expire_date ?? null; // 证件有效期(身份证)
        $params['legalAuthDate'] = $this->legal_auth_date ?? null; // 证件起始日期
        $params['occupation'] = $this->occupation ?? null; // 职业（0001: 国家机关、党群组织、企业、事业单位负责人,0002: 专业技术人员,0003: 办事人员和有关人员,0004: 商业工作人员,0005: 服务性工作人员,0006: 农、林、牧、渔、水利业生产人员,0007: 生产、运输设备操作人员及有关人员,0008: 军人,0009: 不便分类的其他从业人员）
        $params['address'] = $this->address ?? null; // 联系地址
        $params['legalAddress'] = $this->legal_address ?? null; // 证件地址
        $params['issueOffice'] = $this->issue_office ?? null; // 发证机关：XXX公安局
        $fzt->IESI111001($params);
        $hasCustom = static::findOne(['id_no' => $this->id_no]);
        $hasCustomBindUser = $hasCustom ? $hasCustom->bindUser : null;
        switch ($fzt->ret_code){
            case "00000":
                if ($hasCustomBindUser) {
                    LogFengZhangTongSend::doLog($fzt, $hasCustom::className(), $hasCustom->id);
                    return true;
                }
            case "E010010152":
                if ($hasCustomBindUser) {
                    \Yii::$app->session->addFlash("error", "证件信息已存在绑定登录用户名{$hasCustomBindUser->username}，请在后台登录，地址：".Html::a($this->return_url, $this->return_url));
                    LogFengZhangTongSend::doLog($fzt, $hasCustom::className(), $hasCustom->id);
                    return false;
                }
                break;
            default:
                \Yii::$app->session->addFlash("error", "请求分账通异常：".Tools::toJson($fzt->resp_arr));
                LogFengZhangTongSend::doLog($fzt, $this::className());
                return false;
                break;
        }
        $trans = \Yii::$app->db->beginTransaction();
        try {
            if ($hasCustomBindUser){
                $user = $hasCustomBindUser;
            }else{
                $user = new User();
                $user->username = $this->username;
                $user->setPassword($this->password);
                $user->created_at = $user->updated_at = YII_BT_TIME;
                $user->status = $user::STATUS_ACTIVE;
                $user->is_admin_super = $user::IS_ADMIN_SUPER_FALSE;
                $user->email = $this->email;
                $user->phone = $this->mobile_no;
                $user->generateToken();
                if (!$user->save()){
                    \Yii::$app->session->addFlash("error", Model::getModelError($user));
                    return false;
                }
            }
            $this->bind_user_id = $user->id;
            $this->plat_cust_no = $fzt->resp_arr['platCustNo'] ?? null;
            if (!$this->save()) {
                \Yii::$app->session->addFlash("error", Model::getModelError($this));
                return false;
            }
            $bankCard = new CustomBankCard();
            $bankCard->plat_no = $fzt->platNo;
            $bankCard->custom_id = $this->id;
            $bankCard->plat_cust_no = $this->plat_cust_no;
            $bankCard->mobile_no = $this->mobile_no;
            $bankCard->open_bank = $this->open_bank;
            $bankCard->card_no = $this->card_no;
            $bankCard->pay_code = $bankCard::PAY_CODE_051;
            $bankCard->status = $bankCard::STATUS_DEFAULT;
            if (!$bankCard->save()){
                \Yii::$app->session->addFlash("error", Model::getModelError($bankCard));
                return false;
            }
            $trans->commit();
        }catch (\Exception $e){
            $trans->rollBack();
            throw $e;
        }
        LogFengZhangTongSend::doLog($fzt, static::class, $this->id);
        return true;
    }
}